'use strict';
var mock = angular.module('mock', []);
mock.service( 'Http', [ '$http', '$q', function( $http, $q ) {

	var http = function( options ) {
		return $http( options ).then( function( res ) {
			return preproc( res );
		} );
	};

	function preproc( res ) {
		return $q( function(resolve, reject) {
			var err;
			if( res.status != 200 || !res.data ) {
				err = res.status == 404 ? '404 - 访问的地址无效！' : '500 - 服务器内部错误！';
				reject(err);
				return;
			}

			var errCode = parseInt( res.data.err_code );
			if( errCode === 0x00 ) {
				resolve( res.data );
				return;
			}
			reject(err);
		});
	}

	http.get = function( url, config ) {
		return $http.get( url, config ).then( function( res ) {
			return preproc( res );
		} );
	};

	http.post = function( url, data, config ) {
		return $http.post( url, data, config ).then( function( res ) {
			return preproc( res );
		} );
	};

	http.put = function( url, config ) {
		return $http.put( url, config ).then( function( res ) {
			return preproc( res );
		} );
	};

	http.delete = function(url, config) {
		return $http.delete( url, config ).then( function( res ) {
			return preproc( res );
		} );
	};

	return http;
}
] );

var host = 'http://127.0.0.1/api';

function HomeCtrl($scope, http) {
	$scope.clickTest = function () {
		var url = host + '/home';
		http.get(url).then((ret) => {
			console.log({url, ret});
		}).catch((err) => {
			console.log({err});
		});
	}
}
mock.controller("HomeCtrl", ['$scope', 'Http', HomeCtrl]);

function RegionCtrl($scope, http) {
	$scope.getAllProvs = function () {
		var url = host + '/region';
		http.get(url).then((ret) => {
			console.log({url, ret});
		}).catch((err) => {
			console.log({err});
		});
	};

	var pid = '610000'; //陕西
	$scope.getRegionById = function () {
		var url = host + '/region/prov' + '?pid=' + pid;
		http.get(url).then((ret) => {
			console.log({url, ret});
		}).catch((err) => {
			console.log({err});
		});
	};
}
mock.controller("RegionCtrl", ['$scope', 'Http', RegionCtrl]);

function UserCtrl($scope, http) {
}
mock.controller("UserCtrl", ['$scope', 'Http', UserCtrl]);